package nx.simple3d.gui;

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.text.DecimalFormat;

import nx.simple3d.data.Camera;
import nx.simple3d.data.VectorBase;


public class Nx3DCanvas extends Canvas{

  private static final long serialVersionUID = 1L;
  
  private Camera camera;
  private Graphics offscreenGraphics;
  private VectorBase vb;
  private boolean drawFPS = true;
  private long firstFrameMillis = -1;
  private int framesRendered = 0;
  private DecimalFormat fpsFormat = new DecimalFormat("0.00");
  
  
  public Nx3DCanvas(Camera camera){
    super();
    this.camera = camera;
    vb = VectorBase.getInstance();
  }

  @Override
  public void paint(Graphics g) {

  }
  
  public void render(){  
    try {
      offscreenGraphics = getBufferStrategy().getDrawGraphics();
      offscreenGraphics.clearRect(0, 0, getWidth(), getHeight());
      camera.expose(offscreenGraphics, getWidth(), getHeight());
      if(drawFPS) drawFPS(offscreenGraphics);
    }
    finally {
      vb.getSemaphore().release();
      offscreenGraphics.dispose();
    }
   
    getBufferStrategy().show();
    Toolkit.getDefaultToolkit().sync(); 
  }
  
  private void drawFPS(Graphics g){
    if(firstFrameMillis == -1){
      firstFrameMillis = System.currentTimeMillis();
    }
    else{
      double fps = (double)framesRendered / ((double)(System.currentTimeMillis() - firstFrameMillis) / 1000);
      g.drawString("FPS: " + fpsFormat.format(fps), 20, 20);
    }
    
    framesRendered++;
  }
  
  public Camera getCamera(){
    return camera;
  }
}
